package com.nice.common.mweb;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServlet;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyServer {

    private Server server;
    private WebAppContext context;
    private static final long MB_300 = 1024 * 1024 * 300;

    public JettyServer(int port, String contextPath) {

        MultipartConfigElement cfg = new MultipartConfigElement("./", MB_300, MB_300, 262144);
        String useMapped = System.getProperty("useFileMappedBuffer");
        ServletHolder sh = new ServletHolder(UploadServer.class);
        sh.getRegistration().setMultipartConfig(cfg);

        DefaultServlet defaultServlet = new DefaultServlet();
        ServletHolder holder = new ServletHolder(defaultServlet);
        holder.setInitParameter("useFileMappedBuffer", useMapped);

        context = new WebAppContext();
        // context.setContextPath(contextPath);
        context.setParentLoaderPriority(true);
        context.setResourceBase(contextPath);
        context.addServlet(sh, "/upload");
        context.addServlet(holder, "/");
        server = new Server(port);
        server.setHandler(context);
    }

    public void start() throws Exception {
        server.start();
    }

    public void stop() throws Exception {
        server.stop();
    }

    public void join() throws Exception {
        server.join();
    }

    public void addServlet(String path, Class<? extends HttpServlet> servlet) {
        addServlet(path, servlet, new HashMap<String, String>());
    }

    public void addServlet(String path, Class<? extends HttpServlet> servlet, Map<String, String> initArgs) {
        if (!path.startsWith("/"))
            path = "/" + path;
        ServletHolder servletHolder = new ServletHolder(servlet);
        servletHolder.setInitParameters(initArgs);
        context.addServlet(servletHolder, path);
    }

    public static void startWithParam(int port, String webDir) throws Exception {
        new File(webDir).mkdirs();
        JettyServer server = new JettyServer(port, webDir);
        server.start();
        server.join();
    }

    public static void main(String[] args) throws Exception {
        startWithParam(8080, "./res");
    }

}
